package com.manage.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class LoginFilter implements Filter {

	@Override
	public void destroy() {
		
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest  servletRequest =(HttpServletRequest) request;
		HttpServletResponse servletResponse =(HttpServletResponse) response;
		HttpSession session  = servletRequest.getSession();
		
		//获取用户的URL
		String path = servletRequest.getRequestURI();
		//System.err.print(path);
		//从session里取用户名
		String username =(String) session.getAttribute("username");
		System.out.print("过滤器中的用户名"+username);
		//登录页面无需过滤
		if(path.indexOf("/login2.jsp")>-1){
			chain.doFilter(servletRequest,servletResponse);
			return ;
		}
		//判断如果没有取到用户信息，就跳转到登录页面
		if(username ==null||"".equals(username)){
			//跳转到登录页面
			servletResponse.sendRedirect("/chusumanage/views/user.jsp");
		}
			else{
				chain.doFilter(request, response);
		}
	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {
		
	}
}
